#include "ClassroomConfig.h"
#include <json/json.h>
#include <fstream>
#include <string>
ClassroomConfig::ClassroomConfig()
{
}

bool ClassroomConfig::CheckFile()
{
	try
	{
		QString path = QDir::currentPath();
		path +=CONFIGPATH;
		QDir dir(path);
		if (!dir.exists() || !dir.makeAbsolute())
		{
			if (dir.mkdir(path)) {
				createNewConfigFile();
				return false;
			}
			else {
				path = GET_CONFIG_FILE_PATH;
				path += CAMERA_CONFIG_FILE;
				QDir dir_file(path);
				if (!dir_file.exists()) {
					createNewConfigFile();
					return false;
				}
				else return true;
			}
		}
		return true;
	}
	catch (const std::exception&)
	{
		return false;
	}
	
}
bool ClassroomConfig::init() {
	if (CheckFile())
		return true;
	else {
		init();
	}
	return false;
}
bool ClassroomConfig::createNewConfigFile() {
	QString path = GET_CONFIG_FILE_PATH;
	path += CAMERA_CONFIG_FILE;
	QFile fileout(path);
	if (!fileout.open(QIODevice::Append | QIODevice::Text))
	{
		return false;
	}
	QTextStream txtOutput(&fileout);
	txtOutput << DEFAULT_CAMERA_CONFIG_NETWORK;
	fileout.close();
}
QMap<QString, QString> ClassroomConfig::getCameraConfig() {
	QString path = CONFIG_DIR;
	path += CAMERA_CONFIG_FILE;

	std::ifstream json_file_reader;
	QByteArray data = path.toLatin1();
	char *char_path = data.data();
	json_file_reader.open(char_path);
	QMap<QString, QString> Config;
	Json::Reader reader;
	Json::Value root;
	if (!reader.parse(json_file_reader, root, false))
	{
		return Config;
	}
	json_file_reader.close();

	std::string type = root["type"].asCString();
	if (type == "local") {
		Config.insert("type", "local");
		Config.insert("number", root["number"].asCString());
	}
	if (type == "network") {
		Config.insert("type","network");
		Config.insert("password", root["password"].asCString());
		Config.insert("username", root["username"].asCString());
		Config.insert("number", root["number"].asCString());
		Config.insert("port", root["port"].asCString());

		Json::Value ip_address = root["ip"];
		int i = ip_address.size();
		for (int j = 0; j < i; j++) {
			Config.insert(QString::number(j,10), ip_address[std::to_string(j)].asCString());
		}
	}
	return Config;
	
}